/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.infonova.education.microservice.controller;

import com.infonova.education.microservice.exeption.NoContentFoundException;
import com.infonova.education.microservice.exeption.PageNotFoundException;
import com.infonova.education.microservice.repository.entity.Order;
import com.infonova.education.microservice.repository.entity.OrderPosition;
import com.infonova.education.microservice.repository.entity.Product;
import com.infonova.education.microservice.service.OrderService;
import com.infonova.education.microservice.service.ProductService;
import com.itextpdf.text.DocumentException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.text.Position;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author Stefan
 */
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;
    
    @RequestMapping(value = "/cart/{customerId}", method = RequestMethod.POST) // consumes = {"text/*", "application/*"}, 
    public long createOrder(@PathVariable("customerId") long customerID) {
        return orderService.createOrder(customerID);
    }
    
//    @RequestMapping(value = "/createCart", method = RequestMethod.GET) // consumes = {"text/*", "application/*"}, 
//    public long createOrder(@RequestParam("customerID") String customerID) {
//        return orderService.createOrder(Long.valueOf(customerID));
//    }

    @RequestMapping(value = "/cart", method = RequestMethod.PUT)
    public void addPosition(@RequestBody OrderPosition position) {
        orderService.addPosition(position);
    }

    @RequestMapping(value = "/cart", method = RequestMethod.DELETE)
    public void deletePosition(@RequestBody OrderPosition position) throws PageNotFoundException {
        if(orderService.findOrderPositionById(position.getOrderPositionId())==null){
            throw new PageNotFoundException();
        }
        orderService.deletePosition(position);
    }
    
    @RequestMapping(value = "/cart/price", method = RequestMethod.GET)
    public long calculatePrice(@RequestParam("orderId") String orderId) {
        long price = 0;
        Order order = orderService.findOrderById(Long.valueOf(orderId));
        Set<OrderPosition> positions=order.getPositions();
        for (OrderPosition position : positions) {
            Product p = productService.findProductById(position.getProductId());
            price+=p.getPrice()*position.getAnzahl();
        }
        return price;
    }
    
    @RequestMapping(value = "/cart/finish", method = RequestMethod.GET)
    public void finishOrder(@RequestParam("orderId") String orderId){
        orderService.finishOrder(Long.valueOf(orderId));
    }

//    @RequestMapping(value = "/cart", method = RequestMethod.GET)
//    public Order readOrder(@RequestBody long orderID) {
//        return orderService.findOrderById(orderID);
//    }
    @RequestMapping(value = "/cart/{orderID}", method = RequestMethod.GET)
    public Order readOrder(@PathVariable("orderID") long orderID) {
        return convertToXmlSupportingOrder(orderService.findOrderById(orderID));
    }

    @RequestMapping(value = "/cart", method = RequestMethod.GET)
    public Iterable<Order> readAll() throws NoContentFoundException {
        Iterable<Order> old = orderService.findAll();
        if(old.iterator().hasNext()==false){throw new NoContentFoundException();}
        List<Order> updated = new ArrayList<Order>();
        for (Order order : old) {
            updated.add(convertToXmlSupportingOrder(order));
        }
        return updated;
    }
    
    private Order convertToXmlSupportingOrder(Order o1){
        Order o2 = new Order();
        o2.setOrderId(o1.getOrderId());
        o2.setCustomerId(o1.getCustomerId());
        Set<OrderPosition> positions = o1.getPositions();
        Set<OrderPosition> positionsNew = new HashSet<OrderPosition>();
        for (OrderPosition position : positions) {
            positionsNew.add(position);
        }
        o2.setPositions(positionsNew);
        return o2;
    }
        
    @RequestMapping(value = "/cart/print/{orderID}/Order.pdf", method = RequestMethod.GET, consumes = "*", produces = "application/pdf")
    @ResponseBody
    public byte[] printOrder(@PathVariable("orderID") long orderID) throws DocumentException {
        byte[] pdfData = orderService.printOrderByID(orderID);
        return pdfData;
    }

    @ExceptionHandler(DocumentException.class)
    @ResponseBody
    public String handlePdfCreationException(){
        return "Ein cooler Fehler ist aufgetreten.";
    }
}
